/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jmenu.gui;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import jmenu.main.DBQueries;
import jmenu.main.Config;

/**
 *
 * @author Roman
 */
public class Kernel
{
    public DBQueries queries;
    
    private Connection con;
    private String server;
    private String user;
    private String pass;

    public Kernel(String server, String user, String pass)
    {
        this.server = server;
        this.user = user;
        this.pass = pass;
        
        System.setProperty("javax.net.ssl.keyStore","C:/keystore");
        System.setProperty("javax.net.ssl.keyStorePassword","superheslo");
        System.setProperty("javax.net.ssl.trustStore","C:/truststore");
        System.setProperty("javax.net.ssl.trustStorePassword","superheslo");
    } 
    
    private Connection getConnection()
    {
        try
        {
            if (this.con.isClosed())
            {
                this.close();
                this.connect();
                return this.con;
            } 
            else
            {
                return this.con;
            }
        } 
        catch (SQLException ex)
        {
            JOptionPane.showMessageDialog(Config.getMainFrame(), "Nastaly problémy při komunikaci s databází."); 
            return null;
        }
    }

    public boolean connect()
    {
        try
        {
            //Register the JDBC driver for MySQL.
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex)
        {
            JOptionPane.showMessageDialog(Config.getMainFrame(), "Nelze zaregistrovat driver."); 
            return false;
        }
        try
        {       
            //String url ="jdbc:mysql://"+this.server+":3306/jmenu?useSSL=true&requireSSL=true";
            String url ="jdbc:mysql://"+this.server+":3306/jmenuro";
            this.con = DriverManager.getConnection(url,this.user, this.pass);
            this.queries = new DBQueries(this.con);
            return true;
        }
        catch(SQLException ex)
        {   
            JOptionPane.showMessageDialog(Config.getMainFrame(), "Nepodařilo se připojit k databázi."); 
            return false;
        }    
    }

    public boolean isClose()
    {
        try
        {
            return con.isClosed();
        } 
        catch (SQLException ex)
        {
            return true;
        }
    }

    public boolean close()
    {
        try
        {   if(!con.isClosed())
                this.con.close();
            this.con = null;
            return true;
        } 
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(Config.getMainFrame(), "Nepodařilo se validně odpojit od  databáze.");
            
            return false;
        }    
    }
}










